<template>
  <a-select
    :loading="loading"
    placeholder="请选择"
    multiple
    :default-value="defaultValue"
    :filter-option="true"
    :disabled="disabled"
    @search="handleSearch"
    @change="changeMethod"
  >
    <a-option v-for="(item, key) in options" :key="key" :value="item.id">{{
      item.name
    }}</a-option>
  </a-select>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import {
    chargeTypeList,
    departmentList,
    invoiceTypeList,
    payWayList,
    ResultVO,
  } from '@/api/invoice';

  const props = defineProps({
    type: {
      type: String,
      default: '',
    },
    name: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Array,
      default: () => [],
    },
    defaultValue: {
      type: Array,
      default: () => [],
    },
  });
  const loading = ref(false);
  const options = ref<ResultVO[]>([]);
  const defaultOptions = ref<ResultVO[]>([]);
  const emit = defineEmits(['change']);
  const handleSearch = async (value: string) => {
    try {
      loading.value = true;
      if (props.type === 'chargeType') {
        const { data } = await chargeTypeList(value);
        options.value = data;
      } else if (props.type === 'invoiceType') {
        const { data } = await invoiceTypeList();
        options.value = data;
      } else if (props.type === 'department') {
        const { data } = await departmentList();
        options.value = data;
      } else if (props.type === 'payWay') {
        const { data } = await payWayList();
        options.value = data;
      }
      if (defaultOptions.value.length === 0) {
        defaultOptions.value = options.value;
      }
    } catch (e) {
      // you can report use errorHandler or other
    } finally {
      loading.value = false;
    }
  };
  const changeMethod = (value: string[]) => {
    emit('change', { keys: value, options: defaultOptions.value });
  };
  handleSearch('');
</script>

<style scoped lang="less"></style>
